//
//  GAOStatusesListViewModel.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//GAOHomeController 对应的 viewModel
class GAOStatusesListViewModel: NSObject {
    var statusesList: [GAOStatusesViewModel]?
    /**
    获取微博首页数据
    
    - parameter isPullUp: 是否上拉加载
    - parameter complete: 是否成功请求
    */
    func requestStatuses(isPullUp: Bool, complete: (isSuccess: Bool, message: String)->()) {
        var message = "没有加载到更多微博内容"
        //上拉加载使用的默认的maxId
        var maxId: Int64 = 0
        //  下拉刷新使用的默认值
        var sinceId: Int64 = 0
        
        if isPullUp == true {
            //上拉加载要取到数组中最后一条微博的id
            maxId = self.statusesList?.last?.statuses?.id ?? 0
            //因为若指定maxId参数会返回ID小于或等于max_id的微博,有可能加载到重复的微博数据
            if maxId > 0 {
                //去除重复的微博数据
                maxId -= 1
            }
        }else {
            //下拉刷新要取到数组中第一条微博的id
            sinceId = self.statusesList?.first?.statuses?.id ?? 0
//            print(sinceId)
        }
        
        GAOStatusDAL.loadData(maxId, sinceId: sinceId) { (statusesArray) -> () in
            if statusesArray.count == 0 {
                complete(isSuccess: false, message: message)
                return
            }
            //遍历数组初始化模型
            //创建一个GAOStatuses的数组
            var statusesModelArray = [GAOStatusesViewModel]()
            for value in statusesArray {
                let statusesModel = GAOStatuses(dict: value)
                let statusesViewMdoel = GAOStatusesViewModel(statuses: statusesModel)
                statusesModelArray.append(statusesViewMdoel)
            }
            if self.statusesList == nil {
                self.statusesList = [GAOStatusesViewModel]()
            }
            
            
            if isPullUp == true {
                //上拉加载,向数组后追加数据
               self.statusesList = self.statusesList! + statusesModelArray
            } else {
                //在数组前插入数据
                self.statusesList = statusesModelArray + self.statusesList!
            }
            
            if statusesModelArray.count > 0 {
                message = "加载了\(statusesModelArray.count)条数据"
            }
            
            //通过闭包回调数据
            complete(isSuccess: true, message: message)
        }
        
    }

}


